//
//  JPComposeTextView+Extension.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 2016/10/8.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit

extension JPComposeTextView {
    
    //  将textView的富文本转成字符串
    func adjustTextViewEmotionToString() -> String {
        
        guard let attributeText = self.attributedText else {
            return ""
        }
        
        var stringM = ""
        self.attributedText.enumerateAttributes(in: NSMakeRange(0, attributeText.length), options: [], using: { (info, range, _) in
            
            if let attachment = info["NSAttachment"] as? JPTextAttachment {
                //  表示图片
                let chs = attachment.emotion?.chs
                
                stringM += chs!
            }else {
                //  表示文字
                stringM += attributeText.attributedSubstring(from: range).string
            }
        })
        return stringM
    }
    
    func insterEmotion(emotion: JPEmotion) {
        
        if emotion.type == "0" {
            let attributeStringM = NSMutableAttributedString(attributedString: self.attributedText)
            
            let attributedStr = NSAttributedString.attributedStringWithFont(font: self.font!, emotion: emotion)
            
            var range = self.selectedRange
            //  写入富文本
            attributeStringM.replaceCharacters(in: range, with: attributedStr)
            //  这个地方font不解包会崩溃
            attributeStringM.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, attributeStringM.length))
            self.attributedText = attributeStringM
            
            //  改变光标位置
            range.location += 1
            range.length = 0
            self.selectedRange = range
            
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            self.delegate?.textViewDidChange?(self)
            
        }else {
            let emoji = (emotion.code! as NSString).emoji()
            self.insertText(emoji!)
        }
    }
}
